<?php

namespace app\yperp\logic\yp;

use app\yperp\model\GoodsSkuStandby;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use think\Db;

class YpOrder
{
    private static $instance;
    protected $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function token()
    {
        return YpLogin::getInstance()->login('csmb', 'hcyp1234!');
    }
    protected function Request($method = 'POST', $url, $body)
    {
        $client = new Client([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        $headers = [
            'Content-Type' => 'application/json;charset=UTF-8',
            'token' => $this->token(),
        ];
        // $body = '{"page": 1,"limit": 10,"startTime": "2024-02-17","endTime": "2024-03-19"}';
        $body = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $request = new Request($method, $url, $headers, $body);
        $response = $client->sendAsync($request)->wait();
        $data = $response->getBody()->getContents();
        // dump($data);
        $data = json_decode($data, true);
        return $data;
    }
    const ORDER_STATUS_MAP = [
        1 => '待支付',
        2 => '待发货',
        3 => '部分发货',
        4 => '已发货',
        5 => '已收货',
        6 => '已评价',
        7 => '已取消',
        11 => '已完成',
    ];


    const ORDER_PAY_TYPE = [
        1 => '微信支付',
        2 => '余额支付',
        3 => '混合支付',
        4 => '数字人民币',
    ];

    /**
     * 获取订单列表
     * @param string $month_start
     * @param string $month_end
     * @param int $status
     * @return mixed
     */
    protected function getData($DoDayNumber = 5, $status = 0)
    {
        $url = 'https://yp.changhong.com/platform-frame-web-admin/api/orderItem/queryPageList';

        $month_start = date("Y-m-d", strtotime("-{$DoDayNumber} day"));

        $month_end = date("Y-m-d", time());

        dump(['$month_start' => $month_start, '$month_end' => $month_end]);
        $limit = 50;
        $page = 1;

        while (true) {
            $param = [
                'page' => $page,
                'limit' => $limit,
                'startTime' => $month_start,
                'endTime' => $month_end,
            ];
            if ($status) {
                $param['status'] = "$status";
            } else {
                $param['status'] = "";
            }

            $datas = $this->Request('POST', $url, $param);
            dump($datas);

            if ($datas['body']['current'] == ($datas['body']['pages'] + 1)) {
                dump('没有数据了');
                break;
            }
            dump(['pages' => $datas['body']['pages'], '$page' => $page, '$limit' => $limit]);

            $page++;

            yield $datas['body']['records']; // 产出当前的$res值

        }
    }

    function orderGoodsListVoList($datas, $where)
    {
        foreach ($datas as $item) {
            $where['goodsCode'] = $item['goodsCode'];
            $data = Db::name('yperp_yporder_goods')->where($where)->find();
            $item = array_merge($item, $where);



            $expr = JstOrder::getInstance()->getExprCodeOne($where['orderCode']);
            if (!empty($expr)) {
                $item['expr_code'] = $expr['trackNo'];
                $item['expr_corp'] = $expr['expressCompany'];
            } else {
                dump($expr);
            }


            if ($data) {
                Db::name('yperp_yporder_goods')->where($where)->update($item);
            } else {
                Db::name('yperp_yporder_goods')->where($where)->insert($item);
            }
        }
    }

    function getList()
    {
        $datas = $this->getData();

        foreach ($datas as $items) {
            foreach ($items as $key => $item) {
                // dump($item);
                Db::startTrans();
                try {
                    $where = ['mainOrderCode' => $item['mainOrderCode'], 'orderCode' => $item['orderCode']];
                    $this->orderGoodsListVoList($item['orderGoodsListVoList'], $where);
                    unset($item['orderGoodsListVoList']);
                    $data = Db::name('yperp_yporder')->where($where)->find();
                    unset($item['id']);


                    if ($data) {
                        Db::name('yperp_yporder')->where($where)->update($item);
                    } else {
                        Db::name('yperp_yporder')->where($where)->insert($item);
                    }


                    Db::commit();
                } catch (\Throwable $th) {
                    Db::rollback();
                    dump($th->getMessage());
                    dump($th->getTraceAsString());
                }
            }
        }
    }
}
